package com.ggdog.blog.Services.impl;

import com.ggdog.blog.DAO.CommentDAO;

import com.ggdog.blog.POJO.Comment;
import com.ggdog.blog.POJO.Result;
import com.ggdog.blog.POJO.User;

import com.ggdog.blog.POJO.VO.CommentDTO;
import com.ggdog.blog.Services.CommentService;
import com.ggdog.blog.Services.UserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
     CommentDAO commentDAO;
    @Autowired
    UserServices userServices;
    @Override
    public List<CommentDTO> getCommentsByArticleId(int articleId) {
        List<Comment> comments=commentDAO.getCommentsByArticleId(articleId);
        List<CommentDTO> commentDTOS=new ArrayList<>();
        for (int i = 0; i < comments.size(); i++) {
            Comment comment = comments.get(i);
            User user = userServices.getUserById(comment.getUserId());
            CommentDTO commentDTO=new CommentDTO(
                    comment.getCommentId(),
                    comment.getFatherCommentId(),
                    comment.getArticleId(),
                    user.getUserName(),
                    comment.getUserId(),
                    user.getStatus(),
                    comment.getCommentContent(),
                    comment.getCreateTime(),
                    comment.getUpdateTime()
            );
            commentDTOS.add(commentDTO);
        }
        return commentDTOS;
    }

    @Override
    public Result<String> addCommentByArticleId(Map<String, Object> requestData) {
        Comment comment=new Comment(
                (int)requestData.get("fatherCommentId"),
                Integer.parseInt((String)requestData.get("articleId")),
                (int) requestData.get("userId"),
                (String)requestData.get("commentContent")
        );
        int result=commentDAO.addCommentByArticleId(comment);
        if(result==1){
            return Result.success(String.valueOf(comment.getCommentId()));
        }else{
            return Result.error("评论失败");
        }

    }
}
